<?php
namespace App\Services\Message\Message;

use App\Models\Message\Message;
use App\Services\Message\ValidateMessage;
use App\Services\Manage\ManageIndex;
use Illuminate\Support\Facades\DB;
/**
 * @Author: 蒋哲
 * @Date:   2017-05-27 16:25:06
 * @Last Modified by:   ws
 * @Last Modified time: 2018-06-12 
 */
class MessageLogic
{
    /*一对多发送站内信*/
    public function sendBatchMessage($data): array 
    {
        $addContentRes  = (new MessageContentLogic())->addContent($data);
        if($addContentRes['status'] != SUCCESS_STATUS){
            return auto_failure(null,'发送站内信失败');
        }
        // return auto_return([$data, $addContentRes]);
        if(is_array($data['to_uid'])){  //批量发送
            
            //去除发件人自己
            if(in_array($data['from_uid'], $data['to_uid'])){
                unset($data['to_uid'][array_search($data['from_uid'], $data['to_uid'])]);
            }
            $sends = [];
            foreach ($data['to_uid'] as $k => $v) {
                $send['create_time'] = time();
                $send['update_time'] = time();
                $send['from_uid'] = $data['from_uid'];
                $send['to_uid'] = $v;
                $send['content_id'] = $addContentRes['res']['autoRes'];
                $send['status'] = 1;
                $sends[] = $send;
                //$send['orther_info'] = $data['orther_info'];
            }
             $res = Message::insert($sends);
             $res = DB::getPdo()->lastInsertId();
            //$res = $this->model($this->messageModel)->getLastInsID();  这句话返回不了最后插入的id????
        }else{
            $send['create_time'] = time();
            $send['update_time'] = time();
            $send['from_uid'] = $data['from_uid'];
            $send['to_uid'] = $data['to_uid'];
            $send['content_id'] = $addContentRes['res']['autoRes'];
            $send['status'] = 1;
            // $send['orther_info'] = $data['orther_info'];  // 这一行在本地windows可以在linux下不行？
            $res = Message::insertGetId($send);
        }

        return auto_return($res, '发送成功', '发送失败');

    }

    /*db获取某站内信详情*/
    public function dbMessageDetail($data): array 
    {
        $res = Message::join('message_content', 'message_content.id', '=', 'message.content_id')
        ->select('message.*', 'message_content.title', 'message_content.content','message_content.type','message_content.orther_info')
        ->where([['message.id', '=', $data['id']],['message.status', '=', 1]])
        ->whereIn('message.is_del', [0, 1, 2, 3])
        ->first()
        ->toArray();
        $res && $res['orther_info'] = json_decode($res['orther_info'], true);
        return $res;
    }

    /*db获取站内信列表*/
    public function dbMessageList($data): array 
    {
        return Message::whereIn('id', $data['id'])->whereIn('is_del', [0, 1, 2, 3])->where('status', 1)->get()->toArray();
    }

    /*用户、管理员查看某站内信详情  使用视图查询*/
    public function messageDetail($data): array 
    {
        $res = Message::join('message_content', 'message_content.id', '=', 'message.content_id')
        ->select('message.*', 'message_content.title', 'message_content.content','message_content.type','message_content.orther_info')
        ->where([['message.id', '=', $data['id']],['message.status', '=', 1]])
        ->whereIn('message.is_del', [0, 1, 2, 3])
        ->first()
        ->toArray();
        $reply = $this->_getReply(['id'=>$res['reply_ids']]);
        if($res){
            $reply['status'] && $res['reply_contents'] = $reply['res'];
            $res['orther_info'] = json_decode($res['orther_info']);
        }
        isset($data['user_id']) && $setRead = $this->setRead($data);
        return auto_return($res, '获取详情成功', '获取详情失败');
    }

    /*用户将多个站内信设为已读*/
    public function setRead($data): array 
    {
        is_numeric($data['id']) && $data['id'] = [$data['id']];
        $is_read['is_read'] = 1;
        $res =  Message::where([['to_uid', '=', $data['user_id']],['status', '=', 1],['is_read', '=', 0]])
                    ->whereIn('id',$data['id'])
                    ->whereIn('is_del', [0, 1])
                    ->update($is_read);
        return auto_return($res);
    }

    /*获取某站内信的所有回复内容*/
    protected function _getReply($data): array 
    {
        !is_array($data['id']) && $data['id'] = explode(",",$data['id']);
        $res = Message::join('message_content', 'message_content.id', '=', 'message.content_id')
        ->select('message_content.title', 'message_content.content','message_content.type','message_content.orther_info','message_content.create_time')
        ->where([['message.id', '=', $data['id']],['message.status', '=', 1]])
        ->whereIn('message.is_del', [0, 1, 2, 3])
        ->orderBy('message_content.create_time', 'desc')
        ->first();            
        return auto_return($res);

    }

    /*获取某用户未读站内信个数*/
   /* public function noReadCount($data): array 
    {
        $_where['to_uid'] = $data['user_id'];
        $_where['is_read'] = 0;
        $_where['is_del'] = ['in',[0,1]];
        $_where['status'] = 1;
        $res = $this->db()->where($_where)->count();
        return auto_return($res);
    }*/

    /*我回复某个站内信*/
    public function replyOneMessage($data): array 
    {
        $message = $this->dbMessageDetail($data);
        $addData['from_uid'] = $message['to_uid'];
        $addData['to_uid'] = $message['from_uid'];
        $addData['title'] = '回复:【' . $message['title'] . '】';
        $addData['content'] = $data['content'];
        $addData['type'] = $message['type'];
        $addData['orther_info'] = $data['orther_info'];
        $addRes = $this->sendBatchMessage($addData);
        if($addRes['status'] != SUCCESS_STATUS){
            return $addRes;
        }
        $saveData['reply_ids'] = $message['reply_ids'] ? $message['reply_ids'].','.$addRes['res']['autoRes'] : $addRes['res']['autoRes'];
        $res = Message::where('id', $data['id'])->update($saveData); 
       // $res = $this->model($this->messageModel)->save($saveData, ['id'=>$data['id']]);
        return auto_return($res, '回复成功', '回复失败');

    }

    /*管理员批量删除站内信*/
    public function adminDelMessage($data): array 
    {
        is_numeric($data['id']) && $data['id'] = [$data['id']];
        $res = Message::whereIn('id', $data['id'])->whereIn('is_del', [0, 1, 2, 3])->update(['is_del' => 4]);
        return auto_return($res);
    }

    /*用户删除单个站内信*/
    /*public function delOneMessage($data): array 
    {
        $message = $this->dbMessageDetail($data);

        $data['id'] = [$data['id']];
        if($message['from_uid'] == $data['user_id']){
            $res = $this->_sendDelBatchMsg($data);
        }elseif($message['to_uid'] == $data['user_id']) {
            $res = $this->_receiveDelBatchMsg($data);
        }

        return auto_return($res);
    }*/

    /*用户批量删除站内信*/
   /* public function delBatchMessage($data): array 
    {
        
        $asSend = $this->_getIdsAsSend($data);
        $_where['id'] = ['in',$asSend];
        $asSendDel = $this->db()->where($_where)->setInc('is_del',1);

        $asReceive = $this->_getIdsAsReceive($data);
        $_where['id'] = ['in',$asReceive];
        $asReceiveDel = $this->db()->where($_where)->setInc('is_del',2);

        if($asSendDel || $asReceiveDel){
            return auto_success(null,'成功删除站内信');
        }
        return auto_failure(null,'删除站内信失败');
    }*/

    /*获取作为发送者的站内信id数组*/
    /*protected function _getIdsAsSend($data): array 
    {
        $_where['id'] = ['in',$data['id']];
        $_where['from_uid'] = $data['user_id'];
        $_where['is_del'] = ['in',[0,2]];
        $_where['status'] = 1;
        return $this->db()->where($_where)->column('id');
    }*/

    /*获取作为接收者的站内信id数组*/
   /* protected function _getIdsAsReceive($data): array 
    {
        $_where['id'] = ['in',$data['id']];
        $_where['to_uid'] = $data['user_id'];
        $_where['is_del'] = ['in',[0,1]];
        $_where['status'] = 1;
        return $this->db()->where($_where)->column('id');
    }*/

    /*发送者批量删除站内信*/
   /* protected function _sendDelBatchMsg($data): array 
    {
        is_numeric($data['id']) && $data['id'] = [$data['id']];
        $_where['id'] = ['in',$data['id']];
        $_where['is_del'] = ['in',[0,2]];
        $res = $this->db()
                    ->where($_where)
                    ->setInc('is_del',1);
        return auto_return($res);
    }*/

    /*接收方批量删除站内信*/
   /* protected function _receiveDelBatchMsg($data): array 
    {
        is_numeric($data['id']) && $data['id'] = [$data['id']];
        $_where['id'] = ['in',$data['id']];
        $_where['is_del'] = ['in',[0,1]];
        $res = $this->db()
                    ->where($_where)
                    ->setInc('is_del',2);
        return auto_return($res);
    }*/

    /*查看某用户的收件箱或发件箱*/
   /* public function messageList($data): array 
    {

        if($data['msgType'] == 'send'){

            $_where['m.from_uid'] = $data['user_id'];
            $_where['m.is_del'] = ['in', [0,2]];
            $_where['m.status'] = 1;

        }elseif($data['msgType'] == 'receive'){

            $_where['m.to_uid'] = $data['user_id']; 
            $_where['m.is_del'] = ['in', [0,1]];
            $_where['m.status'] = 1;
        }

        $res = $this->model($this->messageModel)
                    ->alias('m')
                    ->field('m.*,mc.title,mc.content,mc.type,mc.orther_info')
                    ->join('__MESSAGE_CONTENT__ mc','mc.id = m.content_id')
                    ->where($_where)
                    ->order('m.create_time desc')
                    ->paginate(null,false,['page'=>$data['page'],'list_rows'=>$data['listRows']])
                    ->toArray();
        if($res['total'] > 0){
            foreach ($res['data'] as $k => &$v) {
                $v['orther_info'] = json_decode($v['orther_info'], true);
            }
        }
        return auto_return_page($res);

    }*/

    /*管理员查看站内信*/
    public function adminMessageList($data): array 
    {
        $keywords = $data['keywords'];
        $user_id = $data['user_id'];
        $re = Message::leftJoin('message_content', 'message_content.id', '=', 'message.content_id')
                     ->select('message.*', 'message_content.title', 'message_content.content','message_content.type','message_content.orther_info')
                     ->where('message.status', '=', 1)
                     ->whereIn('message.is_del', [0,1,2,3]);
             if($user_id){
                $re->where(function($query) use ($user_id){
                $query->where('message.from_uid', '=', $user_id)
                      ->orWhere('message.to_uid', '=', $user_id);});
              }
             if($keywords){
                $re->where(function($query) use ($keywords){
                $query->where('message_content.title','like',"%{$keywords}%")
                      ->orWhere('message.from_uid','like',"%{$keywords}%")
                      ->orWhere('message.to_uid','like',"%{$keywords}%");});
              }
            $res = $re->orderBy('message.create_time', 'desc')
                      ->paginate($data['listRows'], null, null, $data['page'])
                      ->toArray();
        return auto_return_page($res);
    }
 



}